import java.util.Comparator;
import java.util.PriorityQueue;

class ImpDa implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class Solution {
    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k <= 0) {
            return ret;
        }

        //1、建立大小为k的大根堆 O(k*logK)
        PriorityQueue<Integer> priorityQueue2 = new PriorityQueue(new ImpDa());

        //可以采用匿名内部类
        PriorityQueue<Integer> priorityQueue = new PriorityQueue(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }

        //2、遍历剩下的元素 (N-k)*logK
        //总时间复杂度 k*logK + (N-k)*logK = N*logK
        for(int i = k; i < arr.length; i++) {
            int top = priorityQueue.peek();
            if (arr[i] < top) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }

        //下面这个不能算topK时间复杂度，这个地方是整理数据
        for(int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public int[] smallestK2(int[] arr, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < arr.length; i++) {
            priorityQueue.offer(arr[i]);
        }

        int[] ret = new int[k];

        for(int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }

        return ret;

    }
}
